//
//  MoyaExt.swift
//
//
//  Created by Apple on 2017/7/14.
//  Copyright © 2017年 Xwg. All rights reserved.
//
//  MARK: - Moya扩展

import RxSwift
import Moya
import HandyJSON

extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response {
    public func mapModel<T: HandyJSON>(_ type: T.Type, designatedPath path: String? = nil) -> Single<T> {
        return flatMap({ response -> Single<T> in
            return Single.just(try response.mapModel(type, designatedPath: path))
        })
    }
}

extension ObservableType where E == Response {
    public func mapModel<T: HandyJSON>(_ type: T.Type, designatedPath path: String? = nil) -> Observable<T> {
        return flatMap { response -> Observable<T> in
            return Observable.just(try response.mapModel(type, designatedPath: path))
        }
    }
}

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type, designatedPath path: String? = nil) throws -> T {
        
        guard let jsonString = String(data: data, encoding: .utf8) else {
            throw XMoyaError.stringMapping(self)
        }
        
        guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonString, designatedPath: path) else {
            throw XMoyaError.modelMapping(self)
        }
        return model
    }
}
enum XMoyaError: Swift.Error {
    case modelMapping(Response)
    case stringMapping(Response)
}

extension XMoyaError {
    var response: Moya.Response? {
        switch self {
        case .modelMapping(let response): return response
        case .stringMapping(let response): return response
        }
    }
}
